import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/model/medicine_advice_model.dart';
import 'package:ls_work/util/ext_utils.dart';

import '../../../model/building_model.dart';
import '../../../net/response/medicine_advice/take_medicine_list_data.dart';

class TakeMedicineListViewModel
    extends BaseListViewModel<TakeMedicineListData> {
  TakeMedicineListViewModel(super.context);

  String? searchName;

  String? roomName;

  String? medicineName;

  ///服药日期
  String? takeMedicineDate;

  ///状态
  PickerDataWithIdModel? selectedStatus;

  ///服药时间
  PickerDataWithIdModel? takeTime;

  var buildingModel = BuildingModel();

  List<PickerDataWithIdModel> buildingList = [];
  PickerDataWithIdModel? selectedBuilding;
  List<List<PickerDataWithIdModel>> floorList = [];
  PickerDataWithIdModel? selectedFloor;

  var model = MedicineAdviceModel();

  @override
  Future<List<TakeMedicineListData>> requestListData() async {
    if (buildingList.isEmpty) {
      var building = await buildingModel.getBuildingList(rows: 100);
      for (var item in building) {
        buildingList.add(PickerDataWithIdModel(
            pickName: item.buildingNo, pickId: item.id.toString()));
        var list = (item.floorList ?? [])
            .map((e) => PickerDataWithIdModel(
                pickName: e.floorNo, pickId: e.id.toString()))
            .toList();
        list.insert(0, PickerDataWithIdModel(pickName: '全部'));
        floorList.add(list);
      }
    }
    return await model.takeMedicineList(
        customerNameLike: searchName,
        bedNoLike: roomName,
        floorId: selectedFloor?.pickId,
        buildingId: selectedBuilding?.pickId,
        drugNameLike: medicineName,
        planTimeLike: takeMedicineDate,
        status: selectedStatus?.pickId,
        usageTime: takeTime?.pickName,
        page: page,
        rows: pageLength);
    ;
  }

  @override
  void onCreated() {
    super.onCreated();
    requestRefresh();
  }

  void chooseBuildingFloor() {
    DataPickerView(context, buildingList,
        second: floorList,
        currentFirstData: selectedBuilding,
        currentSecondData: selectedFloor, onSubmitListener: (p1, p2, p3) {
      selectedBuilding = buildingList[p1];
      selectedFloor = floorList[p1][p2];
      notifyListeners();
      requestRefresh();
    }).show();
  }

  void chooseTakeDate() {
    var format = [yyyy, '-', mm, '-', dd];
    DatePicker.showDatePicker(context, currentTime: takeMedicineDate?.toDate(),
        onConfirm: (date) {
      takeMedicineDate = date!.toDateStr(format);
      notifyListeners();
      requestRefresh();
    });
  }

  void chooseTakeTime() {
    var items = [
      PickerDataWithIdModel(pickId: '早', pickName: '早'),
      PickerDataWithIdModel(pickId: '中', pickName: '中'),
      PickerDataWithIdModel(pickId: '晚', pickName: '晚'),
      PickerDataWithIdModel(pickId: '睡前', pickName: '睡前'),
    ];
    DataPickerView(context, items, currentFirstData: takeTime,
        onSubmitListener: (p1, p2, p3) {
      takeTime = items[p1];
      notifyListeners();
      requestRefresh();
    }).show();
  }

  void resetClick() {
    searchName = null;
    medicineName = null;
    takeMedicineDate = null;
    selectedStatus = null;
    selectedBuilding = null;
    selectedFloor = null;
    takeTime = null;
    roomName = null;
    notifyListeners();
    requestRefresh();
  }

  void chooseStatus(){
    var items = [
      PickerDataWithIdModel(pickName: '待服药',pickId: '0'),
      PickerDataWithIdModel(pickName: '待核对',pickId: '1'),
      PickerDataWithIdModel(pickName: '已服药',pickId: '2'),
      PickerDataWithIdModel(pickName: '已作废',pickId: '3'),
    ];
    DataPickerView(context, items,currentFirstData: selectedStatus,onSubmitListener: (p1,p2,p3){
      selectedStatus = items[p1];
      notifyListeners();
      requestRefresh();
    }).show();
  }

  void showApplyTakeDialog(int type, TakeMedicineListData item) {
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(
                height: 10,
              ),
              Center(
                child: CommonText(type == 0 ? '核药确认' : '服药确认'),
              ),
              SizedBox(
                height: 18,
              ),
              ...[
                CommonText('${item.drugName??""}',
                    textSize: 17,
                    textColor: Colors.blue,
                    fontWeight: FontWeight.bold),
                CommonText('计划服药日期：${(item.planTime??"").changeTime(format: [yyyy,'-',mm,'-',dd])}'),
                CommonText('药品规格：${item.specifications}'),
                CommonText('单次用量：${item.usageQuantity?.d}${item.minUnitName??""}'),
                Row(
                  children: [
                    CommonText('用量：'),
                    CommonText('${item.usageQuantity?.d}',
                        fontWeight: FontWeight.bold,
                        textSize: 17,
                        textColor: Colors.blue)
                  ],
                ),
                Row(
                  children: [
                    CommonText('服药时间：'),
                    CommonText('${item.usageTime}',
                        fontWeight: FontWeight.bold,
                        textSize: 17,
                        textColor: Colors.blue)
                  ],
                ),
              ].insertWidget(SizedBox(
                height: 10,
              )),
              SizedBox(
                height: 12,
              ),
              Row(
                children: [
                  TextButton(
                    onPressed: () {
                      Go().pop();
                    },
                    child: CommonText('取消', textColor: Colors.blue),
                    style: ButtonStyle(
                      shape: WidgetStateProperty.all(
                          StadiumBorder(side: BorderSide(color: Colors.blue))),
                    ),
                  ).setWeight(1),
                  SizedBox(
                    width: 18,
                  ),
                  TextButton(
                    onPressed: () {
                      // Go().pop();
                      putAndCheck(item.id, type);
                    },
                    child: CommonText('确定', textColor: Colors.white),
                    style: ButtonStyle(
                        shape: WidgetStateProperty.all(StadiumBorder(
                            side: BorderSide(color: Colors.blue))),
                        backgroundColor: WidgetStateProperty.all(Colors.blue)),
                  ).setWeight(1)
                ],
              ),
              SizedBox(
                height: 10,
              )
            ],
          ).addToContainer(
              decoration: BoxDecoration(
                  color: Colors.white, borderRadius: 10.borderRadius),
              padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10)),
        );
      },
    );
  }

  Future<void> putAndCheck(dynamic id,int type) async {
    showLoadingDialog(msg: '提交中...');
    try{
      await model.checkTakeMedicine(ids: [id],type: type);
      hideDialog();
      showToast("提交成功");
      finish();
      requestRefresh();
    }catch(e){
      hideDialog();
      showToast(e.toNetError());
    }
  }

  void cancelTakeMedicine(dynamic id){
    showApplyDialog(context: context, onSubmit: () async {
      showLoadingDialog(msg: '');
      try{
        await model.cancelTakeMedicine(id);
        hideDialog();
        showToast("作废成功");
        requestRefresh();
      }catch(e){
        hideDialog();
        showToast(e.toNetError());
      }
    },message: "确定要作废吗？");
  }

}
